package hip.util.xml;

import java.io.IOException;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XmlUtil {
    public static String formatXml(Document doc) throws IOException {
        StringWriter stringWriter = new StringWriter(); //创建字符串缓冲区
        OutputFormat xmlFormat = new OutputFormat();
        xmlFormat.setEncoding("UTF-8"); //设置文件编码  
        xmlFormat.setIndent(true); // 生成缩进
        xmlFormat.setIndent("    "); // 使用4个空格进行缩进, 可以兼容文本编辑器 
        xmlFormat.setNewlines(true); //设置换行 
        xmlFormat.setNewLineAfterDeclaration(false);//去除空行
        xmlFormat.setTrimText(true);

        XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);//创建写文件方法
        xmlWriter.write(doc);//写入文件    
        xmlWriter.close(); //关闭  
        return stringWriter.toString();// 输出xml 
    }

}
